<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2>我的购物车</h2>
      <p>管理您的订单，享受美食</p>
    </div>

    <div class="cart-content" v-loading="loading">
      <div v-if="cartItems.length === 0" class="empty-cart">
        <el-empty description="购物车是空的">
          <el-button type="primary" @click="$router.push('/store/list')">
            去购物
          </el-button>
        </el-empty>
      </div>

      <div v-else class="cart-items">
        <el-table :data="cartItems" style="width: 100%">
          <el-table-column label="商品信息" min-width="300">
            <template slot-scope="scope">
              <div class="item-info">
                <div class="item-name">{{ scope.row.dishname }}</div>
                <div class="item-price">单价: ¥{{ scope.row.dishprice }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="150">
            <template slot-scope="scope">
              <div class="quantity-controls">
                <el-button 
                  size="mini" 
                  @click="decreaseQuantity(scope.row)"
                  :disabled="scope.row.number <= 1"
                >
                  -
                </el-button>
                <span class="quantity">{{ scope.row.number }}</span>
                <el-button 
                  size="mini" 
                  @click="increaseQuantity(scope.row)"
                >
                  +
                </el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="小计" width="120">
            <template slot-scope="scope">
              <span class="subtotal">¥{{ scope.row.dishprice * scope.row.number }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button 
                type="danger" 
                size="mini" 
                @click="removeItem(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="cart-summary">
          <div class="summary-info">
            <div class="total-items">
              共 {{ totalItems }} 件商品
            </div>
            <div class="total-price">
              总计: <span class="price">¥{{ totalPrice }}</span>
            </div>
          </div>
          <div class="summary-actions">
            <el-button @click="clearCart">清空购物车</el-button>
            <el-button type="primary" @click="checkout">去结算</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCart, updateCartQuantity } from '@/api/cart'
import { mapGetters } from 'vuex'

export default {
  name: 'Cart',
  data() {
    return {
      loading: false,
      cartItems: []
    }
  },
  computed: {
    ...mapGetters(['isLoggedIn', 'userInfo']),
    
    totalItems() {
      return this.cartItems.reduce((total, item) => total + item.number, 0)
    },
    
    totalPrice() {
      return this.cartItems.reduce((total, item) => total + (item.dishprice * item.number), 0)
    }
  },
  methods: {
    async loadCart() {
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      
      this.loading = true
      try {
        const response = await getCart(this.userInfo.userid)
        this.cartItems = response.data.data || []
      } catch (error) {
        this.$message.error('获取购物车失败：' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    async increaseQuantity(item) {
      try {
        await updateCartQuantity(1, item.shopid)
        item.number += 1
        this.$message.success('数量已增加')
      } catch (error) {
        this.$message.error('操作失败：' + error.message)
      }
    },
    
    async decreaseQuantity(item) {
      if (item.number <= 1) return
      
      try {
        await updateCartQuantity(-1, item.shopid)
        item.number -= 1
        this.$message.success('数量已减少')
      } catch (error) {
        this.$message.error('操作失败：' + error.message)
      }
    },
    
    async removeItem(item) {
      try {
        await this.$confirm('确定要删除这个商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 将数量设置为0来删除商品
        await updateCartQuantity(-item.number, item.shopid)
        this.$message.success('商品已删除')
        this.loadCart()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + error.message)
        }
      }
    },
    
    async clearCart() {
      try {
        await this.$confirm('确定要清空购物车吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 逐个删除所有商品
        for (const item of this.cartItems) {
          await updateCartQuantity(-item.number, item.shopid)
        }
        
        this.$message.success('购物车已清空')
        this.loadCart()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('清空失败：' + error.message)
        }
      }
    },
    
    checkout() {
      if (this.cartItems.length === 0) {
        this.$message.warning('购物车是空的')
        return
      }
      
      // 将购物车数据传递到支付页面
      this.$router.push({
        path: '/payment',
        query: {
          total: this.totalPrice,
          items: JSON.stringify(this.cartItems)
        }
      })
    }
  },
  
  mounted() {
    this.loadCart()
  }
}
</script>

<style lang="scss" scoped>
.cart-container {
  padding: 20px;
  
  .cart-header {
    text-align: center;
    margin-bottom: 30px;
    
    h2 {
      font-size: 28px;
      color: #333;
      margin-bottom: 10px;
    }
    
    p {
      color: #666;
      font-size: 16px;
    }
  }
  
  .cart-content {
    .empty-cart {
      text-align: center;
      margin-top: 50px;
    }
    
    .cart-items {
      .item-info {
        .item-name {
          font-weight: bold;
          color: #333;
          margin-bottom: 5px;
        }
        
        .item-price {
          color: #666;
          font-size: 14px;
        }
      }
      
      .quantity-controls {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        
        .quantity {
          min-width: 30px;
          text-align: center;
          font-weight: bold;
        }
      }
      
      .subtotal {
        font-weight: bold;
        color: #e74c3c;
      }
    }
    
    .cart-summary {
      margin-top: 30px;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 8px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .summary-info {
        .total-items {
          color: #666;
          margin-bottom: 5px;
        }
        
        .total-price {
          font-size: 18px;
          
          .price {
            font-weight: bold;
            color: #e74c3c;
            font-size: 24px;
          }
        }
      }
      
      .summary-actions {
        display: flex;
        gap: 15px;
      }
    }
  }
}
</style> 